package bll

import (
	"context"

	"manager/event"
	"manager/model"
	"manager/model/entity"
	"manager/store"
	"manager/store/postgres"
	"time"

	"manager/auth"
)

type alarm struct {
	iAlarm store.IAlarm
}

var Alarm = &alarm{
	iAlarm: postgres.Alarm,
}

func (a *alarm) init() func() {
	return func() {}
}

func (a *alarm) onEvent(*event.Data) {}

// Create 创建
func (a *alarm) Create(ctx context.Context, in *model.AlarmCreateRequest) error {
	var (
		err error
	)

	// 获取用户Id
	in.UserId, _ = auth.ContextUserID(ctx)

	// 构建创建现场数据
	c := buildAlarm(in)
	_, err = a.iAlarm.Create(ctx, c)
	return err
}

// Update 更新
func (a *alarm) Update(ctx context.Context, in *model.AlarmUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	updateAt := time.Now().Unix()
	in.UpdatedAt = &updateAt

	if in.UserId != nil {
		dict["user_id"] = in.UserId
	}

	if in.Type != nil {
		dict["type"] = in.Type
	}

	if in.EbikeId != nil {
		dict["ebike_id"] = in.EbikeId
	}

	if in.EbikeTypeId != nil {
		dict["ebike_type_id"] = in.EbikeTypeId
	}

	if in.EbikeTypeName != nil {
		dict["ebike_type_name"] = in.EbikeTypeName
	}

	if in.Level != nil {
		dict["level"] = in.Level
	}

	if in.UpdatedAt != nil {
		dict["updated_at"] = in.UpdatedAt
	}

	// do other update here
	return a.iAlarm.Update(ctx, in.Id, dict)
}

// Delete 删除
func (a *alarm) Delete(ctx context.Context, in *model.AlarmDeleteRequest) error {
	return a.iAlarm.Delete(ctx, in.Id)
}

// AlarmTimes 获取报警次数
func (a *alarm) AlarmTimes(ctx context.Context, ebikeId, alarmType int64) (count int64) {
	db := postgres.GetDB(ctx).Model(&entity.Alarm{}).Where("ebike_id = ?", ebikeId)
	if alarmType > 0 {
		db = db.Where("type = ?", alarmType)
	}
	db.Count(&count)
	return
}

// List 列表查询
func (a *alarm) List(ctx context.Context, in *model.AlarmListRequest) (*model.AlarmListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.Alarm
		out   = &model.AlarmListResponse{}
	)

	if total, list, err = a.iAlarm.List(ctx, in); err != nil {
		return nil, err
	}

	out.Total = total
	out.List = model.AlarmsEntityToDto(list)

	return out, nil
}

// Find 列表查询
func (a *alarm) Find(ctx context.Context, in *model.AlarmInfoRequest) (*model.AlarmInfo, error) {
	var (
		err  error
		data *entity.Alarm
		out  = &model.AlarmInfo{}
	)

	if data, err = a.iAlarm.Find(ctx, in); err != nil {
		return nil, err
	}

	out = model.AlarmEntityToDto(data)
	return out, nil
}

// buildAlarm 构建创建数据现场
func buildAlarm(in *model.AlarmCreateRequest) *entity.Alarm {
	// todo: check the entity is required
	return &entity.Alarm{

		UserId: in.UserId,

		Type: in.Type,

		EbikeId: in.EbikeId,

		EbikeTypeId: in.EbikeTypeId,

		EbikeTypeName: in.EbikeTypeName,

		FrameCode: "",

		ControlId: 0,

		Level: in.Level,

		Score: 0,

		CreatedAt: time.Now().Unix(),

		UpdatedAt: time.Now().Unix(),
	}
}
